package cn.yunhe.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import cn.yunhe.entity.User;
import cn.yunhe.util.DButil;

public class UserDaoImpl implements IUserDao {
	Connection con = null;
	PreparedStatement ps = null;
	ResultSet rs = null;
	public	int addUser(String username,String password,String email,String phone,String provience,int academic ) {	
		String sql = "insert into GAOKAOUSER values(user_seq.nextval,?,?,?,?,?,?)";
		Object[] pramas = {email,password,provience,academic,username,phone};
		return DButil.insertOrDelOrUpdate(sql, pramas);
	}

	@Override
	public User searchUser(String username) {
			User user = new User();
		try {
			con = DButil.getCon();
			
			String sql = "select * from GAOKAOUSER where username = '"+username+"'";
			ps = con.prepareStatement(sql);
			
			rs = ps.executeQuery();
			if(rs.next()){
				user.setEmail(rs.getString("email"));
				user.setProvinces(rs.getString("provinces"));
				user.setPwd(rs.getString("pwd"));
				user.setUserid(rs.getInt("userid"));
				user.setUsername(rs.getString("username"));
				user.setUserphone(rs.getString("userphone"));
				user.setWenorli(rs.getInt("wenorli"));
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DButil.close(con, ps, rs);
		}
		return user;
	}

	@Override
	public int updateUser(String sql,Object[] pramas) {
		return DButil.insertOrDelOrUpdate(sql, pramas);
	}

	@Override
	public List<User> getAll() {
		List<User> list = new ArrayList<>();
		
		try {
			String sql = "select * from GAOKAOUSER";
			con = DButil.getCon();
			ps=con.prepareStatement(sql);
			rs=ps.executeQuery();
			while(rs.next()){
				User user = new User();
				user.setEmail(rs.getString("email"));
				user.setProvinces(rs.getString("provinces"));
				user.setPwd(rs.getString("pwd"));
				user.setUserid(rs.getInt("userid"));
				user.setUsername(rs.getString("username"));
				user.setUserphone(rs.getString("userphone"));
				user.setWenorli(rs.getInt("wenorli"));
				
				list.add(user);
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			DButil.close(con, ps, rs);
		}
		return list;
	}

	@Override
	public int delUser(int userid) {
		String sql = "delete from GAOKAOUSER where userid = ?";
		Object[] pramas = {userid};
		return DButil.insertOrDelOrUpdate(sql, pramas);
	}

}
